//
//  LoginViewController.m
//  BombAbility
//
//  Created by oscar chinellato on 26/02/10.
//  Copyright 2010 __MyCompanyName__. All rights reserved.
//

#import "LoginViewController.h"
#import "MainViewController.h"




@implementation LoginViewController


@synthesize username;
@synthesize password;
@synthesize resultLabel;
@synthesize connection;
@synthesize mainController;
@synthesize currentParsedData;
@synthesize parsedBombs;
@synthesize receivedData;
@synthesize loginView;
@synthesize registrationView;


-(IBAction) login {
	
	//NSString *stringaRisultato = [NSString stringWithFormat:@"%d",t];
	//[lblTotale setText:stringaRisultato];
	
	NSLog(@"Inizio Connessione");
	
	
	
	NSString *user = [username text];
	NSString *pass = [password text];
	
	if(![user isEqualToString:@""]) {
	
		NSString *urlString = [NSString stringWithFormat: @"http://www.sickdevelopers.com/BombAbility/login.php?username=%@&password=%@",user, pass];
		//NSString *urlString = @"http://www.google.it";
		
		NSLog(@"Richiesta: %@", urlString);
		
		NSURL *url = [NSURL URLWithString:urlString];
		
		
		NSURLRequest *request = [NSURLRequest requestWithURL:url];
		assert(request != nil);
		
		NSURLConnection *connection = [NSURLConnection connectionWithRequest:request delegate:self];
		
		NSLog(@"Connessione avviata");
		
		self.connection = connection;
		
		self.receivedData = [[NSMutableData alloc] retain];

	}
	
	else {
		[mainController startResumeScreen:self];
	}
	
	//[conn release];
	//[resultLabel setText:test];
	
}

#pragma mark NSURLConnection delgate methods

- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response {
	
	// cast della risposta ad una risposta HTTP per gestire gli stati
	NSHTTPURLResponse *httpResponse = (NSHTTPURLResponse *) response;
	
	if(httpResponse.statusCode == 200) {
		
		NSLog(@"Risposta ricevuta 200");
		
		MainViewController *parent = (MainViewController*) self.mainController;
		assert(parent != nil);
		
		
		
	}
	
	//[httpResponse release];
	
	
}

- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data {
	
	[receivedData appendData:data];
	
	NSLog(@"Dati ricevuti: %@", receivedData);
	
	// creazione del parser don i dati ricevuti
	NSXMLParser *parser = [[NSXMLParser alloc] initWithData:data];
	
	// reset delle variabili del parser
	currentParsedData = [[NSMutableString alloc] initWithUTF8String:""];
	isParsing = NO;
	isParsingBombs = NO;
	
	// inizializzazione del parser
	[parser setDelegate:self];
	[parser parse];
	
	// release della memoria del parser
	[parser release];
	
}

#pragma mark NSXMLParser constants & vars

static NSString * const loginResultElement = @"loginResult";
static NSString * const userElement = @"user";
static NSString * const usernameElement = @"name";
static NSString * const bombsElement = @"bombs";
static NSString * const receivedElement = @"received";
static NSString * const dropDateElement = @"dropDate";
static NSString * const defuseStringElement = @"defusedString";
static NSString * const timeLimitElement = @"timeLimit";




#pragma mark NSXMLParser delegate methods

- (void)parser:(NSXMLParser *)parser didStartElement:(NSString *)elementName namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qName attributes:(NSDictionary *)attributeDict {
	
	//NSLog(@"DidStart %@", elementName);
	
	
	// parsing del risultato del login
	if([elementName isEqualToString:loginResultElement]) {
		[currentParsedData setString:@""];
		isParsing = YES;
	}
	
	// parsing dell'utente
	if([elementName isEqualToString:userElement]) {
		NSLog(@"ID utente : %@", [attributeDict valueForKey:@"id"]);
		// in questo punto deve essere creato l'oggetto User e poi 
		// i suoi campi devono essere popolati con gli altri tag 
		// dell'xml ricevuto
		User *u = [[User alloc] init];
		[u initWithUserId:[attributeDict valueForKey:@"id"]];
		[mainController setUser:u];
		// inizializzo il campo dati per tenere temporanamente 
		// le bombe parsate
		//parsedBombs = [[NSMutableArray alloc] init];
	}
	
	// parsing del nome utente
	if([elementName isEqualToString:usernameElement]) {
		[currentParsedData setString:@""];
		isParsing = YES;
	}
	
	//parsing della root bombs
	if([elementName isEqualToString:bombsElement]) {
		NSLog(@"Ricevuta una bomba!");
		// creazione della bomba, popolata allo stesso modo dello user
		Bomb *aBomb = [[Bomb alloc] init ];
		[aBomb initWithBombId:[attributeDict valueForKey:@"id"]];
		//[parsedBombs  ]
		isParsingBombs = YES;
	}

	//parsing defuse String 
	if([elementName isEqualToString:defuseStringElement]) {
		
	}
	
}



- (void)parser:(NSXMLParser *)parser didEndElement:(NSString *)elementName namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qName {
	
	// parsing del risultato del login
	if([elementName isEqualToString:loginResultElement]) {
		NSLog(@"Login Result %@", currentParsedData);
		
		// gestione degli esiti del login
		// CASO OK
		if([currentParsedData isEqualToString:@"OK"]) {
			[mainController startResumeScreen:self];
		}
		// CASO fail
		else if([currentParsedData isEqualToString:@"fail"]) {
			[mainController startRegistrationScreen:self];
		}
		//resetto la stringa buffer del parsing
		[currentParsedData setString:@""];
		
	}
	
	// parsing del nome utente
	if([elementName isEqualToString:usernameElement]) {
		NSLog(@"Username Result %@", currentParsedData);
		
		//aggiungo all'utente creato prima il suo nome
		[mainController.user setUserName:currentParsedData];
		
	}
	
	//parsing della root bombs
	if([elementName isEqualToString:bombsElement]) {
		
	}
	// ora non sta più parsando
	isParsing = NO;
	
}


- (void)parser:(NSXMLParser *)parser foundCharacters:(NSString *)string {
	
	if(isParsing) {
		NSLog(@"parsing %@", string);
		// aggiungo ai dati correntemente parsati la stringa contenuta dal nodo XML
		[currentParsedData appendString:string];
		NSLog(@"CurrentParsedData : %@", currentParsedData);
	}
	
}


/*
 // The designated initializer.  Override if you create the controller programmatically and want to perform customization that is not appropriate for viewDidLoad.
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil {
    if (self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil]) {
        // Custom initialization
    }
    return self;
}
*/





/*
// Override to allow orientations other than the default portrait orientation.
- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation {
    // Return YES for supported orientations
    return (interfaceOrientation == UIInterfaceOrientationPortrait);
}
*/

#pragma mark UIViewController Override methods

- (IBAction)killKeyboard:(UITextField *)textField {
	
	[textField resignFirstResponder];
	
}

- (BOOL)textFieldShouldReturn:(UITextField *)textField {
	[textField resignFirstResponder];
	return YES;
}


- (void)didReceiveMemoryWarning {
	// Releases the view if it doesn't have a superview.
    [super didReceiveMemoryWarning];
	
	// Release any cached data, images, etc that aren't in use.
}

- (void)viewDidUnload {
	// Release any retained subviews of the main view.
	// e.g. self.myOutlet = nil;
}

// Implement viewDidLoad to do additional setup after loading the view, typically from a nib.
- (void)viewDidLoad {
	
    [super viewDidLoad];
}


- (void)dealloc {
    [super dealloc];
}


@end
